package com.feng.gulimall.product.service.impl;

import com.alibaba.nacos.api.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.feng.common.to.SkuInformationTo;
import com.feng.common.to.SpuBoundsTo;
import com.feng.gulimall.product.entity.SkuImagesEntity;
import com.feng.gulimall.product.entity.SkuInfoEntity;
import com.feng.gulimall.product.entity.SkuSaleAttrValueEntity;
import com.feng.gulimall.product.feign.CouponFeign;
import com.feng.gulimall.product.service.*;
import com.feng.gulimall.product.vo.save.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.feng.common.utils.PageUtils;
import com.feng.common.utils.Query;

import com.feng.gulimall.product.dao.SpuInfoDao;
import com.feng.gulimall.product.entity.SpuInfoEntity;
import org.springframework.transaction.annotation.Transactional;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    private SpuInfoDescService spuInfoDescService;

    @Autowired
    private SpuImagesService spuImagesService;

    @Autowired
    private ProductAttrValueService productAttrValueService;

    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    private SkuInfoService skuInfoService;

    @Autowired
    private SkuImagesService skuImagesService;
    @Autowired
    private CouponFeign couponFeign;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    // 保存提交过来的商品信息
    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo spuSaveVo) {
        // spu的基本信息  pms_spu_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuSaveVo, spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        baseMapper.insert(spuInfoEntity);
        Long spuId = spuInfoEntity.getId();   // 保存之后，拿到id

        // spu的描述信息  pms_spu_info_desc
        List<String> decript = spuSaveVo.getDecript();
        spuInfoDescService.saveDesc(spuId, decript);

        // spu的图像信息  pms_spu_images
        List<String> images = spuSaveVo.getImages();
        spuImagesService.saveImages(spuId, images);

        // spu的积分信息  sms_spu_bounds    远程服务调用
        Bounds bounds = spuSaveVo.getBounds();
        SpuBoundsTo spuBoundsTo = new SpuBoundsTo();
        BeanUtils.copyProperties(bounds, spuBoundsTo);
        spuBoundsTo.setSpuId(spuId);
        couponFeign.saveBounds(spuBoundsTo);

        // spu的规格参数  pms_product_attr_value
        List<BaseAttrs> baseAttrs = spuSaveVo.getBaseAttrs();
        productAttrValueService.saveAttrValue(spuId, baseAttrs);

        // spu的sku信息
        List<Skus> skus = spuSaveVo.getSkus();

        // sku的基本信息  pms_sku_info
        skus.stream().forEach((sku) -> {
            String img = "";
            for (Images image : sku.getImages()) {
                if (image.getDefaultImg() == 1){
                    img = image.getImgUrl();
                }
            }
            SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
            BeanUtils.copyProperties(sku, skuInfoEntity);
            skuInfoEntity.setSpuId(spuId);
            skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
            skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
            skuInfoEntity.setSkuDefaultImg(img);
            skuInfoEntity.setSaleCount(0L);
//            skuInfoEntity.setSkuDesc(spuInfoEntity.getSpuDescription());
            // 保存基本信息
            skuInfoService.save(skuInfoEntity);

            // sku的图片信息  pms_sku_images
            List<SkuImagesEntity> imagesEntities = sku.getImages().stream().map((item) -> {
                SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                skuImagesEntity.setSkuId(skuInfoEntity.getSkuId());
                skuImagesEntity.setImgUrl(item.getImgUrl());
                skuImagesEntity.setDefaultImg(item.getDefaultImg());
                return skuImagesEntity;
            }).filter((entity) -> {
                // 过滤掉空的图片数据
                return !StringUtils.isBlank(entity.getImgUrl());
                    })
                    .collect(Collectors.toList());
            skuImagesService.saveBatch(imagesEntities);

            // sku的销售属性信息  pms_sku_sale_attr_value
            List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = sku.getAttr().stream().map((attr) -> {
                SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                BeanUtils.copyProperties(attr, skuSaleAttrValueEntity);
                skuSaleAttrValueEntity.setSkuId(skuInfoEntity.getSkuId());
                return skuSaleAttrValueEntity;
            }).collect(Collectors.toList());
            skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);
            // sku的优惠等信息
            SkuInformationTo skuInformationTo = new SkuInformationTo();
            BeanUtils.copyProperties(sku, skuInformationTo);
            skuInformationTo.setSkuId(skuInfoEntity.getSkuId());
            couponFeign.saveInfo(skuInformationTo);
            // sku的折扣信息  sms_sku_ladder

            // sku的满减信息  sms_sku_full_reduction

            // 会员价格信息  sms_member_price

        });



    }

    @Override
    public PageUtils queryPageByCondetion(Map<String, Object> params) {
        LambdaQueryWrapper<SpuInfoEntity> wrapper = new LambdaQueryWrapper<>();
        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isBlank(catelogId) && !"0".equals(catelogId)){
            wrapper.eq(SpuInfoEntity::getCatalogId, catelogId);
        }
        String brandId = (String) params.get("brandId");
        if(!StringUtils.isBlank(brandId) && !"0".equals(brandId)){
            wrapper.eq(SpuInfoEntity::getBrandId, brandId);
        }
        String status = (String) params.get("status");
        if (!StringUtils.isBlank(status)){
            wrapper.eq(SpuInfoEntity::getPublishStatus, status);
        }
        String key = (String) params.get("key");
        if (!StringUtils.isBlank(key)){
            wrapper.and((w) -> {
                w.eq(SpuInfoEntity::getId, key).or().like(SpuInfoEntity::getSpuName, key);
            });
        }

        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);

    }

}
